package com.concurrent.coline.part2.threadlocal;

import java.util.Arrays;

/**
 * 类说明：演示ThreadLocal的使用
 */
public class UseThreadLocal {
	
	//可以理解为 一个map，类型 Map<Thread,Integer>
	private static ThreadLocal<Integer> threadLaocl = ThreadLocal.withInitial(() -> 1);

    /**
     *类说明：测试线程，线程的工作是将ThreadLocal变量的值变化，并写回，看看线程之间是否会互相影响
     */
    public static class TestThread implements Runnable{
        int id;
        private TestThread(int id){
            this.id = id;
        }

        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName()+":start");
            //获得变量的值
            Integer s = threadLaocl.get();
            s = s+id;
            threadLaocl.set(s);
            System.out.println(Thread.currentThread().getName()+":"+threadLaocl.get());
            threadLaocl.remove();
            System.out.println(Thread.currentThread().getName()+": After remove :"+threadLaocl.get());
        }
    }

    /**
     * 运行3个线程
     */
    private void StartThreadArray(){
        Thread[] runs = new Thread[3];
        for(int i=0;i<runs.length;i++){
            runs[i]=new Thread(new TestThread(i));
        }
        Arrays.stream(runs).forEach(
                Thread::start
        );
    }

    public static void main(String[] args){
    	UseThreadLocal test = new UseThreadLocal();
        test.StartThreadArray();
    }
}
